package com.aacar.interceptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.JoinPoint;

public class AspectUtil {

	public static  Map<String, Object> convertParams(JoinPoint joinPoint) throws IllegalAccessException, InvocationTargetException {
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		Class<?> cls = joinPoint.getTarget().getClass();
		Object[] params = joinPoint.getArgs();
		Method[] methods = cls.getMethods();
		String methodName = joinPoint.getSignature().getName();
		for (Method m : methods) {
			if (m.getName().equals(methodName)) {
				Annotation[][] paramAnnotations = m.getParameterAnnotations();
				Class<?>[] paramClazzs = m.getParameterTypes();
				Map requestHeaderMap = new HashMap();
				Map requestBodyMap = new HashMap();
				Map requestParamMap = new HashMap();
				for (int i = 0; i < paramClazzs.length; i++) {
					Annotation[] pAnnotation = paramAnnotations[i];
					Class ownerClass = pAnnotation[0].annotationType();
					Method[] methodss = ownerClass.getMethods();

					String paramKey = ownerClass.getSimpleName();
					if ("RequestHeader".equals(paramKey)) {
						if (paramClazzs[i] == Map.class) {
							requestHeaderMap.putAll((Map) params[i]);
						} else {
							for (Method mm : methodss) {
								if (mm.getName().equals("value")) {
									String paramKey2 = (String) mm.invoke(pAnnotation[0], null);
									requestHeaderMap.put(paramKey2, params[i]);
									break;
								}
							}
						}
					} else if ("RequestBody".equals(paramKey)) {
						//requestBodyMap.putAll((Map) params[i]);
					} else if ("RequestParam".equals(paramKey)) {
						String paramKey2 = "";
						for (Method mm : methodss) {
							if (mm.getName().equals("value")) {
								paramKey2 = (String) mm.invoke(pAnnotation[0], null);
								break;
							}
						}
						if ("".equals(paramKey2)) {
							requestParamMap.put(paramKey + "" + i, params[i]);
						} else {
							requestParamMap.put(paramKey2, params[i]);
						}
					}

				}
				requestBodyMap.putAll(requestParamMap);
				paramsMap.put("RequestHeader", requestHeaderMap);
				//paramsMap.put("RequestBody", requestBodyMap);
				break;
			}
		}
		return paramsMap;
	}

}
